import React, { useState, useEffect } from 'react';
import { motion } from 'framer-motion';
import { MapPin, Navigation, AlertCircle, RefreshCw } from 'lucide-react';
import { useAuthStore } from '../stores';
import { useNavigate } from 'react-router-dom';
import { apiService } from '../services/api';
import toast from 'react-hot-toast';
import type { NearbyUser } from '../types/api';

const NearbyUsersPage: React.FC = () => {
  const { user } = useAuthStore();
  const navigate = useNavigate();
  const [nearbyUsers, setNearbyUsers] = useState<NearbyUser[]>([]);
  const [isLoading, setIsLoading] = useState(false);
  const [currentLocation, setCurrentLocation] = useState<{ lat: number; lng: number } | null>(null);
  const [radius, setRadius] = useState(10); // 默认10公里
  const [showManualInput, setShowManualInput] = useState(false);
  const [manualLat, setManualLat] = useState('');
  const [manualLng, setManualLng] = useState('');

  // 获取用户当前位置
  const getCurrentLocation = () => {
    return new Promise<{ latitude: number; longitude: number }>((resolve, reject) => {
      if ('geolocation' in navigator) {
        const options = {
          enableHighAccuracy: true, // 尝试获取更精确的位置
          timeout: 10000, // 10秒超时
          maximumAge: 0 // 不使用缓存的位置
        };
        
        navigator.geolocation.getCurrentPosition(
          (position) => {
            resolve({
              latitude: position.coords.latitude,
              longitude: position.coords.longitude,
            });
          },
          (error) => {
            console.error('Geolocation error:', error);
            // 提供详细的错误信息
            let errorMessage = '无法获取位置';
            switch(error.code) {
              case 1: // PERMISSION_DENIED
                errorMessage = '位置权限被拒绝，请点击地址栏左侧图标允许位置访问';
                break;
              case 2: // POSITION_UNAVAILABLE
                errorMessage = '位置信息不可用，请检查网络和定位服务';
                break;
              case 3: // TIMEOUT
                errorMessage = '获取位置超时，请检查网络连接';
                break;
              default:
                errorMessage = `无法获取位置 (错误码: ${error.code})`;
            }
            reject(new Error(errorMessage));
          },
          options
        );
      } else {
        reject(new Error('Geolocation is not supported'));
      }
    });
  };

  // 更新用户位置
  const updateUserLocation = async (lat: number, lng: number) => {
    if (!user) return;

    try {
      await apiService.updateLocation({
        user_id: user.user_id,
        latitude: lat,
        longitude: lng,
        city: '', // 可以留空或通过反向地理编码获取
        address: '',
      });
    } catch (error) {
      console.error('Update location error:', error);
      // 不显示错误，因为这不是用户主动操作
    }
  };

  // 获取附近的人
  const fetchNearbyUsers = async () => {
    if (!user || !currentLocation) return;

    setIsLoading(true);
    try {
      const response = await apiService.getNearbyUsers({
        user_id: user.user_id,
        latitude: currentLocation.lat,
        longitude: currentLocation.lng,
        radius: radius,
      });

      if (response.code === 0 && response.data.users) {
        setNearbyUsers(response.data.users);
      } else {
        toast.error('获取附近用户失败');
      }
    } catch (error) {
      console.error('Fetch nearby users error:', error);
      toast.error('获取附近用户失败');
    } finally {
      setIsLoading(false);
    }
  };

  // 初始化位置并获取附近用户
  useEffect(() => {
    const initLocation = async () => {
      // 直接使用默认位置，不阻塞用户
      const defaultLocation = { lat: 39.9042, lng: 116.4074 };
      setCurrentLocation(defaultLocation);
      updateUserLocation(defaultLocation.lat, defaultLocation.lng);
      
      // 后台尝试获取真实位置
      try {
        const location = await getCurrentLocation();
        setCurrentLocation({ lat: location.latitude, lng: location.longitude });
        await updateUserLocation(location.latitude, location.longitude);
        console.log('Successfully got location:', location);
      } catch (error) {
        // 静默失败，继续使用默认位置
        console.log('Location not available, using default location');
        // 不显示错误提示，保持用户体验流畅
      }
    };

    initLocation();
  }, [user]);

  // 当位置或半径改变时，获取附近用户
  useEffect(() => {
    if (currentLocation) {
      fetchNearbyUsers();
    }
  }, [currentLocation, radius]);

  const handleRefresh = async () => {
    setIsLoading(true);
    try {
      const location = await getCurrentLocation();
      setCurrentLocation({ lat: location.latitude, lng: location.longitude });
      
      await updateUserLocation(location.latitude, location.longitude);
      await fetchNearbyUsers();
      toast.success('位置已更新为当前位置');
    } catch (error) {
      console.error('Refresh location error:', error);
      // 保持使用当前位置或默认位置
      if (currentLocation) {
        await fetchNearbyUsers();
        toast.success('已刷新附近用户');
      }
    } finally {
      setIsLoading(false);
    }
  };

  const formatDistance = (km: number): string => {
    if (km < 1) {
      return `${Math.round(km * 1000)}m`;
    }
    return `${km.toFixed(1)}km`;
  };

  const handleManualLocation = () => {
    const lat = parseFloat(manualLat);
    const lng = parseFloat(manualLng);
    
    if (isNaN(lat) || isNaN(lng)) {
      toast.error('请输入有效的经纬度');
      return;
    }
    
    if (lat < -90 || lat > 90) {
      toast.error('纬度必须在 -90 到 90 之间');
      return;
    }
    
    if (lng < -180 || lng > 180) {
      toast.error('经度必须在 -180 到 180 之间');
      return;
    }
    
    setCurrentLocation({ lat, lng });
    setShowManualInput(false);
    updateUserLocation(lat, lng);
    toast.success('位置已手动设置');
  };

  return (
    <div className="min-h-screen bg-gray-50 pt-20">
      <div className="max-w-md mx-auto px-4">
        {/* 页面标题 */}
        <motion.div
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          className="text-center mb-6"
        >
          <h1 className="text-2xl font-bold text-gray-900 mb-2">附近的人</h1>
          <div className="flex flex-col items-center space-y-2">
            <div className="flex items-center space-x-2 text-gray-600">
              <MapPin size={16} />
              <span className="text-sm">
                {currentLocation ? '已获取位置' : '正在获取位置...'}
              </span>
            </div>
            {currentLocation && (
              <div className="text-xs text-gray-500">
                经纬度: {currentLocation.lat.toFixed(4)}, {currentLocation.lng.toFixed(4)}
              </div>
            )}
          </div>
          
          {/* 提示信息 */}
          <motion.div
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            className="bg-green-50 border border-green-200 rounded-lg p-3 mt-4 text-left"
          >
            <div className="flex items-start space-x-2">
              <AlertCircle size={16} className="text-green-600 mt-0.5 flex-shrink-0" />
              <div className="text-sm text-green-700">
                <div className="font-medium mb-1">💡 当前位置：</div>
                <div className="text-xs space-y-1">
                  <div>• {currentLocation ? `已设置位置 (${currentLocation.lat.toFixed(2)}, ${currentLocation.lng.toFixed(2)})` : '正在获取...'}</div>
                  <div>• 需要切换到其他城市？点击"手动"按钮设置</div>
                  <div>• 想使用真实位置？点击"刷新"按钮</div>
                </div>
              </div>
            </div>
          </motion.div>
        </motion.div>

        {/* 搜索半径控制 */}
        <motion.div
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ delay: 0.1 }}
          className="bg-white rounded-xl p-4 shadow-sm mb-4"
        >
          <div className="flex items-center justify-between mb-3">
            <div className="flex items-center space-x-2">
              <Navigation size={18} className="text-gray-600" />
              <span className="text-sm font-medium text-gray-700">搜索半径</span>
            </div>
            <div className="flex items-center space-x-2">
              <button
                onClick={() => setShowManualInput(!showManualInput)}
                className="flex items-center space-x-1 text-sm text-gray-600 hover:text-primary-600"
              >
                <MapPin size={14} />
                <span>{showManualInput ? '隐藏' : '手动'}</span>
              </button>
              <button
                onClick={handleRefresh}
                disabled={isLoading}
                className="flex items-center space-x-2 text-sm text-primary-600 hover:text-primary-700 disabled:opacity-50"
              >
                <RefreshCw size={16} className={isLoading ? 'animate-spin' : ''} />
                <span>刷新</span>
              </button>
            </div>
          </div>
          
          <div className="flex items-center space-x-4">
            <input
              type="range"
              min="1"
              max="50"
              value={radius}
              onChange={(e) => setRadius(Number(e.target.value))}
              className="flex-1"
            />
            <span className="text-sm font-medium text-gray-700 w-16 text-right">
              {radius}km
            </span>
          </div>

          {/* 手动输入位置 */}
          {showManualInput && (
            <motion.div
              initial={{ opacity: 0, height: 0 }}
              animate={{ opacity: 1, height: 'auto' }}
              exit={{ opacity: 0, height: 0 }}
              className="mt-4 pt-4 border-t border-gray-200"
            >
              <p className="text-sm text-gray-600 mb-3">手动设置位置（可选）</p>
              <div className="grid grid-cols-2 gap-3">
                <div>
                  <label className="block text-xs text-gray-600 mb-1">纬度</label>
                  <input
                    type="number"
                    value={manualLat}
                    onChange={(e) => setManualLat(e.target.value)}
                    placeholder="例如: 39.9042"
                    step="0.0001"
                    min="-90"
                    max="90"
                    className="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-primary-500"
                  />
                </div>
                <div>
                  <label className="block text-xs text-gray-600 mb-1">经度</label>
                  <input
                    type="number"
                    value={manualLng}
                    onChange={(e) => setManualLng(e.target.value)}
                    placeholder="例如: 116.4074"
                    step="0.0001"
                    min="-180"
                    max="180"
                    className="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-primary-500"
                  />
                </div>
              </div>
              <div className="mt-3 flex space-x-2">
                <button
                  onClick={handleManualLocation}
                  className="flex-1 px-4 py-2 bg-primary-500 hover:bg-primary-600 text-white rounded-lg text-sm font-medium transition-colors duration-200"
                >
                  设置位置
                </button>
                <button
                  onClick={() => setShowManualInput(false)}
                  className="px-4 py-2 bg-gray-100 hover:bg-gray-200 text-gray-700 rounded-lg text-sm font-medium transition-colors duration-200"
                >
                  取消
                </button>
              </div>
              <p className="text-xs text-gray-500 mt-2">
                💡 常用城市：北京 (39.9042, 116.4074) | 上海 (31.2304, 121.4737) | 深圳 (22.5431, 114.0579)
              </p>
            </motion.div>
          )}
        </motion.div>

        {/* 附近用户列表 */}
        {isLoading ? (
          <div className="flex items-center justify-center py-12">
            <div className="text-center">
              <div className="w-8 h-8 border-2 border-primary-500 border-t-transparent rounded-full animate-spin mx-auto mb-4"></div>
              <p className="text-gray-600">正在查找附近的人...</p>
            </div>
          </div>
        ) : nearbyUsers.length === 0 ? (
          <motion.div
            initial={{ opacity: 0, y: 20 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ delay: 0.2 }}
            className="bg-white rounded-xl p-8 text-center"
          >
            <AlertCircle className="text-gray-400 mx-auto mb-4" size={48} />
            <h3 className="text-lg font-semibold text-gray-900 mb-2">附近暂无用户</h3>
            <p className="text-gray-600 text-sm mb-4">
              尝试扩大搜索半径或稍后再来
            </p>
            <button
              onClick={() => setRadius(Math.min(radius + 10, 50))}
              className="btn-primary"
            >
              扩大范围
            </button>
          </motion.div>
        ) : (
          <motion.div
            initial={{ opacity: 0, y: 20 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ delay: 0.2 }}
            className="space-y-3"
          >
            <p className="text-sm text-gray-600 mb-2">
              找到 <span className="font-semibold text-primary-600">{nearbyUsers.length}</span> 个附近的人
            </p>
            
            {nearbyUsers.map((item, index) => (
              <motion.div
                key={item.user_id}
                initial={{ opacity: 0, y: 20 }}
                animate={{ opacity: 1, y: 0 }}
                transition={{ delay: index * 0.05 }}
                className="bg-white rounded-xl p-4 shadow-sm hover:shadow-md transition-shadow duration-200"
              >
                <div className="flex items-center space-x-4">
                  {/* 头像 */}
                  <img
                    src={item.avatar || '/api/placeholder/60/60'}
                    alt={item.nickname}
                    className="w-16 h-16 rounded-full object-cover"
                  />
                  
                  {/* 用户信息 */}
                  <div className="flex-1 min-w-0">
                    <h3 className="text-lg font-semibold text-gray-900 mb-1">
                      {item.nickname}
                    </h3>
                    
                    <div className="flex items-center space-x-4 text-sm text-gray-600 mb-2">
                      {item.age && (
                        <span>{item.age}岁</span>
                      )}
                      {item.distance && (
                        <span className="flex items-center">
                          <MapPin size={14} className="mr-1" />
                          {formatDistance(item.distance)}
                        </span>
                      )}
                    </div>
                    
                    {item.bio && (
                      <p className="text-sm text-gray-600 line-clamp-2">
                        {item.bio}
                      </p>
                    )}
                    
                    {/* 兴趣标签 */}
                    {item.interests && item.interests.length > 0 && (
                      <div className="flex flex-wrap gap-1 mt-2">
                        {item.interests.slice(0, 3).map((interest) => (
                          <span
                            key={interest.tag_id}
                            className="px-2 py-0.5 bg-primary-100 text-primary-700 rounded-full text-xs"
                          >
                            {interest.tag_name}
                          </span>
                        ))}
                        {item.interests.length > 3 && (
                          <span className="px-2 py-0.5 bg-gray-100 text-gray-600 rounded-full text-xs">
                            +{item.interests.length - 3}
                          </span>
                        )}
                      </div>
                    )}
                  </div>
                  
                  {/* 查看详情按钮 */}
                  <motion.button
                    whileHover={{ scale: 1.05 }}
                    whileTap={{ scale: 0.95 }}
                    onClick={() => navigate('/home')}
                    className="px-4 py-2 bg-primary-500 hover:bg-primary-600 text-white rounded-lg transition-colors duration-200 text-sm font-medium"
                  >
                    查看
                  </motion.button>
                  <motion.button
                    whileHover={{ scale: 1.05 }}
                    whileTap={{ scale: 0.95 }}
                    onClick={async () => {
                      if (!user) return;
                      try {
                        await apiService.addFriend({ user_id: user.user_id, target_user_id: item.user_id });
                        toast.success('已发送好友添加');
                      } catch (e) {
                        toast.error('添加好友失败');
                      }
                    }}
                    className="ml-2 px-4 py-2 bg-green-500 hover:bg-green-600 text-white rounded-lg transition-colors duration-200 text-sm font-medium"
                  >
                    添加好友
                  </motion.button>
                </div>
              </motion.div>
            ))}
          </motion.div>
        )}
      </div>
    </div>
  );
};

export default NearbyUsersPage;

